package com.hjm.project.settleInfo.settleInfo.service.impl;

import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.security.ShiroUtils;
import com.hjm.common.utils.trade.TranddleUtil;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.project.settleInfo.settleInfo.mapper.SettleInfoMapper;
import com.hjm.project.settleInfo.settleInfo.service.ISettleInfoService;
import com.hjm.project.walletDetails.walletDetails.domain.WalletDetails;
import com.hjm.project.walletDetails.walletDetails.mapper.WalletDetailsMapper;
import com.hjm.project.walletDetails.walletDetails.utils.SendUtils;
import com.yxhd.encrypt.EncryptUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 清结算信息
 *
 * @author LOVE
 * @date 2020-11-23
 */
@Service
public class SettleInfoServiceImpl implements ISettleInfoService {

    @Resource
    private SettleInfoMapper settleInfoMapper;
    @Autowired
    private WalletDetailsMapper walletDetailsMapper;

    @Override
    public List<Map<String, Object>> unPayList(Map<String, Object> params) throws Exception{
        List<Map<String, Object>> list=settleInfoMapper.getUnPayPageList(params);
        if (list.size()>0){
            for (Map<String, Object> map : list) {
                String cscreen_num=map.get("SCREEN_NUM").toString();
                String jmscreen_num= EncryptUtils.getDecrypt(cscreen_num);
                String screen_num=jmscreen_num.substring(0,6)+"****"+jmscreen_num.substring(jmscreen_num.length()-4);
                map.put("SCREEN_NUM",screen_num);
            }
        }
        return list;
    }
    public List<Map<String, Object>> getMerPaiList(Map<String, Object> params) throws Exception{
        List<Map<String, Object>> list = settleInfoMapper.getMerPaiList(params);
        return list;
    }

    /**
     * 代付对账查询
     * @Param [params]
     * @Return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     */
    public List<Map<String,Object>> tradeNoQsList(Map<String,Object> params) throws Exception {
        return settleInfoMapper.tradeNoQsList(params);
    }


    @Override
    public List<Map<String, Object>> getDateOrdernumber(Map<String, Object> params) {
        return settleInfoMapper.getDateOrdernumber(params);
    }

    @Override
    public List<Map<String, Object>> getOrderPageList(Map<String, Object> params) {
        return settleInfoMapper.getOrderPageList(params);
    }

    @Override
    public List<Map<String, Object>> showNoqingsuan(Map<String, Object> params) {
        return settleInfoMapper.showNoqingsuan(params);
    }

    @Override
    public List<Map<String, Object>> showNoqingsuanOnline(Map<String, Object> params) {
        return settleInfoMapper.showNoqingsuanOnline(params);
    }

    @Override
    public List<Map<String, Object>> showNoChukuan(Map<String, Object> params) {
        return settleInfoMapper.showNoChukuan(params);
    }

    @Override
    public List<Map<String, Object>> getUnpayTranddelList(Map<String, Object> params) throws Exception{
        List<Map<String, Object>> list=settleInfoMapper.getUnpayTranddelList(params);
        if (list.size()>0){
            for (Map<String, Object> map : list) {
                String screenNum=String.valueOf(map.get("SCREEN_NUM"));
                 screenNum=EncryptUtils.getDecrypt(screenNum);
                 screenNum=screenNum.substring(0, 6)+"****"+screenNum.substring(screenNum.length() - 4);
                 map.put("SHOW_SCREENNUM", screenNum);
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getDeductPageList(Map<String, Object> params) {
        return settleInfoMapper.getDeductPageList(params);
    }

    @Override
    public List<Map<String, Object>> getRemittanceBillsList(Map<String, Object> params) {
        return settleInfoMapper.getRemittanceBillsList(params);
    }

    @Override
    public List<Map<String, Object>> getMerchantUnPay(Map<String, Object> params) {
        return settleInfoMapper.getMerchantUnPay(params);
    }

    @Override
    public List<Map<String, Object>> getPayAbleList(Map<String, Object> params) {
        return settleInfoMapper.getPayAbleList(params);
    }


    /** 交易未清算 **/
    @Override
    public Map<String,String> saveQingsuan(String serials,String type) throws Exception{
        Map<String,String> resultMap=new HashMap<>();
        try {
            Map<String,Object> paramMap=new HashMap<>();

            //查询是否是交易未清算的
            String[] serialArr=serials.split(",");
            paramMap.put("serialArr",serialArr);
            paramMap.put("status0","0");
            paramMap.put("status1","1");
            paramMap.put("au_state",0);

            List<Map<String,Object>> serialMapList=settleInfoMapper.getSerialByQs(paramMap);
            if (serialMapList==null || serialMapList.size()==0){
                //没有符合 交易未清算的交易数据
                resultMap.put("result","1");
                resultMap.put("resultMsg","未匹配到该交易数据");
                return resultMap;
            }
            int successCount=0;
            //推送计费接口
            for (Map<String,Object> tmpMap : serialMapList){
                String serial=tmpMap.get("SERIAL")+"";
                String sett_type=tmpMap.get("SETT_TYPE")==null?"":tmpMap.get("SETT_TYPE").toString();
                Integer mertype=Integer.parseInt(tmpMap.get("MER_TYPE").toString());
                TranddleUtil.send(serial,Integer.parseInt(type),sett_type,mertype,null,tmpMap.get("AMOUNT").toString(),"H007");
                successCount++;
            }
            if (successCount==0){
                resultMap.put("result","1");
                resultMap.put("resultMsg","上送失败");
            }else{
                resultMap.put("result","0");
                resultMap.put("resultMsg","上送成功!总笔数："+serialArr.length+",成功笔数："+successCount);
            }
        } catch (Exception e) {
            throw e;
        }
        return resultMap;
    }


    /** 交易未清算 线上 **/
    @Override
    public Map<String,String> saveQingsuanOnline(String serials,String type) throws Exception{
        Map<String,String> resultMap=new HashMap<>();
        try {
            Map<String,Object> paramMap=new HashMap<>();

            //查询是否是交易未清算的
            String[] serialArr=serials.split(",");
            paramMap.put("serialArr",serialArr);
            paramMap.put("status0","00");
            paramMap.put("status1","01");
            paramMap.put("au_state","0");

            List<Map<String,Object>> serialMapList=settleInfoMapper.getSerialByQsOnline(paramMap);
            if (serialMapList==null || serialMapList.size()==0){
                //没有符合 交易未清算的交易数据
                resultMap.put("result","1");
                resultMap.put("resultMsg","未匹配到该交易数据");
                return resultMap;
            }
            int successCount=0;
            //推送计费接口
            for (Map<String,Object> tmpMap : serialMapList){
                String serial=tmpMap.get("SERIAL")+"";
                String sett_type=tmpMap.get("SETTLE_TYPE")==null?"":tmpMap.get("SETTLE_TYPE").toString();
                String mertype = tmpMap.get("MER_TYPE").toString();
                String msgtype = tmpMap.get("MSGTYPE").toString();
                TranddleUtil.send(serial,Integer.parseInt(type),sett_type,null,null,tmpMap.get("AMOUNT").toString(),msgtype);
                successCount++;
            }
            if (successCount==0){
                resultMap.put("result","1");
                resultMap.put("resultMsg","上送失败");
            }else{
                resultMap.put("result","0");
                resultMap.put("resultMsg","上送成功!总笔数："+serialArr.length+",成功笔数："+successCount);
            }
        } catch (Exception e) {
            throw e;
        }
        return resultMap;
    }

    /**
     * 出款解冻
     * @Param [params]
     * @Return int
     */
    @Override
    public int saveThawStatus(Map<String, Object> params) throws Exception {
        int result = 0;
        try {
            String[] ids = String.valueOf(params.get("ids")).split(",");
            for (String id : ids) {
                //查看当前状态是否正确 只有-3可解冻
                Map param = new HashMap();
                param.put("id",id);
                Map<String, Object> getThawStatusOne = settleInfoMapper.getThawStatus(param);
                if (!"-3".equals(String.valueOf(getThawStatusOne.get("SETTLE_STATE")))) {
                    throw new BusinessException("只有出款状态为冻结才可进行解冻,非冻结状态出款流水:" + getThawStatusOne.get("SETTLE_SERIAL"));
                }
            }
            params.put("serialArr",ids);
            result = settleInfoMapper.saveThawStatus(params);
        } catch (NumberFormatException e) {
            throw e;
        }
        return result;
    }

    /**
     * 清结算管理,出款补录,补录通知
     * @Param [params]
     * @Return int
     */
    @Override
    public int saveBuLu(Map<String, Object> params) throws Exception {
        int result = 0;
        try {
            //获取商户上游编号
            Map<String, Object> oneMap = settleInfoMapper.getMerLdMerno(String.valueOf(params.get("mer_no")));

            //查询钱宝对账表qb_mer_withdrawal trad_status为空或非 00 的交易
            params.put("mer_no",oneMap.get("LD_MERNO"));
            Map<String, Object> getDzInfo = settleInfoMapper.getDzInfo(params);
            //如果没有交易记录
            if (MapUtils.isNotEmpty(getDzInfo)) {
                throw new BusinessException("当前数据不可补录");
            }

            Map<String, Object> payInfo = new HashMap<>();
            //线下
            if ("1".equals(String.valueOf(params.get("type")))) {
                //获取当前交易的交易信息
                payInfo = settleInfoMapper.getPayInfo(params);
                if (MapUtils.isEmpty(payInfo)) {
                    throw new BusinessException("获取不到交易信息");
                }
            }

            //线上
            if ("2".equals(String.valueOf(params.get("type")))) {
                //获取当前交易的交易信息
                payInfo = settleInfoMapper.getPayOnLineInfo(params);
                if (MapUtils.isEmpty(payInfo)) {
                    throw new BusinessException("获取不到交易信息");
                }
            }

            Map<String,Object> insert = new HashMap<>();
            insert.put("localdatetime",payInfo.get("LOCALDATE"));
            insert.put("mer_no",payInfo.get("BNO"));
            insert.put("ori_sys",payInfo.get("STAN"));
            result = settleInfoMapper.insertDzInfo(insert);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }


    /**
     * 清结算管理,出款补录,解冻通知
     * @Param [params]
     * @Return int
     */
    @Override
    public int saveJieDong(Map<String, Object> params) throws Exception {
        int result = 0;
        try {
            //获取商户上游编号
            Map<String, Object> oneMap = settleInfoMapper.getMerLdMerno(String.valueOf(params.get("mer_no")));

            params.put("mer_no",oneMap.get("LD_MERNO"));
            //查询钱宝对账表qb_mer_withdrawal trad_status非 00 的交易
            Map<String, Object> getDzInfo = settleInfoMapper.getDzInfo(params);

            //如果没有交易记录
            if (MapUtils.isEmpty(getDzInfo)) {
                throw new BusinessException("请先补录交易数据");
            }
            if (String.valueOf(getDzInfo.get("TRAD_STATUS")).equals("00")) {
                throw new BusinessException("不可对成功的交易进行操作");
            }


            Map<String,Object> update = new HashMap<>();
            update.put("localdatetime",getDzInfo.get("LOCALDATETIME"));
            update.put("mer_no",getDzInfo.get("MER_NO"));
            update.put("ori_sys",getDzInfo.get("ORI_SYS"));
            update.put("trad_status","00");
            result = settleInfoMapper.updateDzInfo(update);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }



    /**
     * 重新手动入账
     * @Param [serials, type]
     * @Return java.util.Map<java.lang.String, java.lang.String>
     */
    @Override
    public Map<String,String> saveInputMoney(String serials,String type) throws Exception{
        Map<String,String> resultMap=new HashMap<>();
        try {
            Map<String,Object> paramMap=new HashMap<>();

            //查询是否是交易未清算的
            String[] serialArr=serials.split(",");
            paramMap.put("serialArr",serialArr);
            paramMap.put("entry_state1","-1");
            paramMap.put("entry_state2","0");
            List<Map<String,Object>> serialMapList = settleInfoMapper.getInputMoney(paramMap);
            if (serialMapList==null || serialMapList.size()==0){
                //没有符合 交易未清算的交易数据
                resultMap.put("result","1");
                resultMap.put("resultMsg","未匹配到需手动入账数据");
                return resultMap;
            }
            int successCount=0;
            //推送计费接口
            for (Map<String,Object> tmpMap : serialMapList){
                String serial = tmpMap.get("SERIAL")+"";
                String sett_type = tmpMap.get("SETT_TYPE")==null?"":tmpMap.get("SETT_TYPE").toString();
                TranddleUtil.sendInputMoney(serial,Integer.parseInt(type),null,null,sett_type,tmpMap.get("AMOUNT").toString(),"H007");
                successCount++;
                Thread.sleep(500);
            }
            if (successCount==0){
                resultMap.put("result","1");
                resultMap.put("resultMsg","上送失败");
            }else{
                resultMap.put("result","0");
                resultMap.put("resultMsg","上送成功!总笔数："+serialArr.length+",成功笔数："+successCount);
            }
        } catch (Exception e) {
            throw e;
        }
        return resultMap;
    }


    @Override
    public int updateMerPaid(String settle_state,String note,String settle_serial) {
        return settleInfoMapper.updateMerPaid(settle_state,note,settle_serial);
    }

    @Override
    public AjaxResult saveCkReject(Map<String, String> params) {
        String[] ids = params.get("ids").split(",");
        List<Map> list = new ArrayList<>();
        for (String id : ids) {
            Map query = new HashMap();
            query.put("id",id);
            List<Map> unPayPageList = settleInfoMapper.getUnPayPageList(query);
            if (CollectionUtils.isEmpty(unPayPageList)) {
                return AjaxResult.error("出款流水号不存在");
            }

            Map result = unPayPageList.get(0);
            Integer settle_state = Integer.parseInt(result.get("SETTLE_STATE").toString());
            if (settle_state == 1) {
                return AjaxResult.error(result.get("SETTLE_SERIAL") + " 已出款成功,不可操作");
            }

            if (settle_state == -4) {
                return AjaxResult.error(result.get("SETTLE_SERIAL") + " 已被打回,不可操作");
            }

            list.add(result);
        }

        for (Map info : list) {
            String settleSerial = info.get("SETTLE_SERIAL").toString();
            WalletDetails wd = new WalletDetails();
            wd.setProfitSerial(settleSerial);
            List<WalletDetails> walletDetails = walletDetailsMapper.selectPaymentList(wd);
            if (CollectionUtils.isEmpty(walletDetails)) {
                return AjaxResult.error("未获取到该订单的出款明细信息," + settleSerial);
            }
            WalletDetails wtd = walletDetails.get(0);

            String merno = info.get("MERNO").toString();
            String money = wtd.getAmount();
            String adjustType = "1";
            String accountType = wtd.getAcType();
            AjaxResult ajaxResult = SendUtils.adjustAgentMoney(merno, money, adjustType, accountType);
            if (Integer.parseInt(ajaxResult.get("code").toString()) != 0) {
                return AjaxResult.error("出款流水" + settleSerial + "打回失败," + ajaxResult.get("msg"));
            }
            int i = settleInfoMapper.updateMerPaid("-4", ShiroUtils.getLoginName() + "进行出款打回", settleSerial);
            if (i == 0) {
                return AjaxResult.error("出款流水" + settleSerial + "打回失败");
            }
        }
        return AjaxResult.success();
    }
}
